<template>
    <view class="captcha-input-content">
        <up-input v-model="captchaValue" placeholder="请输入验证码" border="none" @change="change" />
        <view class="captcha-btn">
            <up-button shape="circle" @click="getCaptcha" :disabled="captchaBtnDisabled">{{captchaBtnTxt}}</up-button>
        </view>
    </view>
</template>

<script setup lang="ts">
    import { ref,reactive } from 'vue';
import { CaptchaPhoneReq } from '../http/common';
import { MyAlert } from '../utils/utils';

    const props= defineProps({
        modelValue:String,
        phone:String
    })

    const captchaValue=ref(props.modelValue)
    const captchaBtnDisabled=ref(false)
    const captchaBtnTxt=ref("获取验证码")
    const captchaExpird=ref(0)

    const emit=defineEmits(["update:modelValue","afterGetCaptcha"])

    const getCaptcha=()=>{
        CaptchaPhoneReq({phone:props.phone}).then((res)=>{
            emit("afterGetCaptcha",res.data)
            captchaBtnDisabled.value=true
            captchaExpird.value=60
            captchaBtnTxt.value=captchaExpird.value+"秒"
            const inv=setInterval(()=>{
                captchaExpird.value--
                captchaBtnTxt.value=captchaExpird.value+"秒"
                if(captchaExpird.value<0){
                    captchaBtnTxt.value="获取验证码"
                    captchaBtnDisabled.value=false
                    clearInterval(inv)
                }
            },1000)
        }).catch(res=>{
            MyAlert({title:"获取验证码失败",content:res.data.msg})
        })
        
    }

    const change=(e)=>{
        emit("update:modelValue",e)
    }

</script>

<style lang="scss" scoped>
    .captcha-input-content{
        display: flex;
        .captcha-btn{
            margin-left: 20upx;
            width: 192upx;
        }
    }
</style>